package com.bcx.crm.spring.websocket.webSocket1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: ys
 * @Date:Create in 2018/5/14 14:35
 * @Description: Handler 处理类
 */
public class ChatWebSocketHandler extends TextWebSocketHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>());

    //接受消息，并发送消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        chatTextMessageHandler(message.getPayload());
        super.handleTextMessage(session, message);
    }

    //链接建立后处理
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.debug("connect to the websocket chat success......");
        sessions.add(session);
//        super.afterConnectionEstablished(session);
        //处理离线消息
    }

    //抛出异常时处理
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()){
            session.close();
        }
        logger.debug("websocket chat connection closed......");
        sessions.remove(session);
//        super.handleTransportError(session, exception);
    }

    //连接关闭后处理
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.debug("websocket chat connection closed......");
        sessions.remove(session);
//        super.afterConnectionClosed(session, status);
    }

    @Override
    public boolean supportsPartialMessages() {
//        return super.supportsPartialMessages();
        return false;
    }
}
